package org.jash.exam.view

import android.Manifest
import android.content.Context
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.SDKInitializer
import com.baidu.mapapi.map.BaiduMap
import com.baidu.mapapi.map.BitmapDescriptor
import com.baidu.mapapi.map.BitmapDescriptorFactory
import com.baidu.mapapi.map.MapStatusUpdateFactory
import com.baidu.mapapi.map.MapView
import com.baidu.mapapi.map.MarkerOptions
import com.baidu.mapapi.map.MyLocationConfiguration
import com.baidu.mapapi.map.MyLocationData
import com.baidu.mapapi.model.LatLng
import com.example.exam.databinding.ActivityMapactivityBinding
import com.example.lib_base.mvvm.BaseViewActivity
import java.text.SimpleDateFormat
import java.util.*

@Route(path = "/exam/MAPActivity")
class MAPActivity : BaseViewActivity<ActivityMapactivityBinding>() {
    
    // 百度地图相关变量
    private lateinit var mapView: MapView
    private lateinit var baiduMap: BaiduMap
    private lateinit var locationClient: LocationClient
    private var isFirstLocation = true
    
    // SharedPreferences用于存储位置信息
    private lateinit var sharedPreferences: SharedPreferences
    
    // 权限请求码
    companion object {
        private const val LOCATION_PERMISSION_REQUEST_CODE = 1001
        private val REQUIRED_PERMISSIONS = arrayOf(
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        )
    }
    
    override fun initView() {
        // 设置百度地图隐私政策同意状态（必须在SDK初始化前调用）
        SDKInitializer.setAgreePrivacy(applicationContext, true)
        
        // 初始化百度地图SDK
        SDKInitializer.initialize(applicationContext)
        
        // 初始化SharedPreferences
        sharedPreferences = getSharedPreferences("location_data", Context.MODE_PRIVATE)
        
        // 初始化地图视图
        mapView = binding.mapView
        baiduMap = mapView.map
        
        // 设置地图类型为普通地图
        baiduMap.mapType = BaiduMap.MAP_TYPE_NORMAL
        
        // 开启定位图层
        baiduMap.isMyLocationEnabled = true
        
        // 设置默认地图中心点（北京天安门）和缩放级别
        val defaultLocation = LatLng(39.915, 116.404)
        val mapStatus = MapStatusUpdateFactory.newLatLngZoom(defaultLocation, 12f)
        baiduMap.setMapStatus(mapStatus)
        
        // 启用地图手势操作
        val uiSettings = baiduMap.uiSettings
        uiSettings.isCompassEnabled = true // 显示指南针
        uiSettings.isScrollGesturesEnabled = true // 允许滑动手势
        uiSettings.isZoomGesturesEnabled = true // 允许缩放手势
        
        // 显示地图缩放控件
        mapView.showZoomControls(true)
        
        // 设置定位按钮点击事件
        binding.btnLocation.setOnClickListener {
            checkPermissionsAndStartLocation()
        }
        
        // 检查权限并初始化定位
        checkPermissionsAndStartLocation()
        
        // 加载之前保存的位置信息
        loadSavedLocationInfo()
    }
    
    override fun initData() {
        // 数据初始化相关操作
    }
    
    /**
     * 检查权限并开始定位
     */
    private fun checkPermissionsAndStartLocation() {
        val missingPermissions = REQUIRED_PERMISSIONS.filter {
            ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED
        }
        
        if (missingPermissions.isNotEmpty()) {
            // 请求权限
            ActivityCompat.requestPermissions(
                this,
                missingPermissions.toTypedArray(),
                LOCATION_PERMISSION_REQUEST_CODE
            )
        } else {
            // 权限已授予，开始定位
            initLocationClient()
        }
    }
    
    /**
     * 初始化定位客户端
     */
    private fun initLocationClient() {
        try {
            // 设置定位服务隐私政策同意状态
            LocationClient.setAgreePrivacy(true)
            
            // 创建定位客户端
            locationClient = LocationClient(applicationContext)
            
            // 配置定位参数
            val option = LocationClientOption().apply {
                locationMode = LocationClientOption.LocationMode.Hight_Accuracy // 高精度模式
                setCoorType("bd09ll") // 百度坐标系
                setScanSpan(0) // 单次定位
                setIsNeedAddress(true) // 需要地址信息
                setIsNeedLocationDescribe(true) // 需要位置描述
                setNeedDeviceDirect(false) // 不需要设备方向
                isLocationNotify = false // 不需要位置提醒
                setIgnoreKillProcess(true) // 忽略kill进程
                setIsNeedLocationDescribe(true) // 需要位置描述
                setIsNeedAltitude(false) // 不需要海拔信息
                setEnableSimulateGps(false) // 不允许模拟GPS
            }
            
            // 设置定位参数
            locationClient.locOption = option
            
            // 注册定位监听器
            locationClient.registerLocationListener(object : BDAbstractLocationListener() {
                override fun onReceiveLocation(location: BDLocation?) {
                    handleLocationResult(location)
                }
            })
            
            // 开始定位
            locationClient.start()
            
            Toast.makeText(this, "开始定位...", Toast.LENGTH_SHORT).show()
            
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "定位初始化失败: ${e.message}", Toast.LENGTH_LONG).show()
        }
    }
    
    /**
     * 处理定位结果
     */
    private fun handleLocationResult(location: BDLocation?) {
        if (location == null) {
            Toast.makeText(this, "定位失败，请检查网络和GPS设置", Toast.LENGTH_LONG).show()
            return
        }
        
        when (location.locType) {
            BDLocation.TypeGpsLocation,
            BDLocation.TypeNetWorkLocation,
            BDLocation.TypeOffLineLocation -> {
                // 定位成功
                val latitude = location.latitude
                val longitude = location.longitude
                val address = location.addrStr ?: "地址解析失败"
                val currentTime = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(Date())
                
                // 更新地图显示
                updateMapLocation(latitude, longitude)
                
                // 更新UI显示
                updateLocationUI(latitude, longitude, address, currentTime)
                
                // 保存位置信息到SharedPreferences
                saveLocationToSP(latitude, longitude, address, currentTime)
                
                Toast.makeText(this, "定位成功", Toast.LENGTH_SHORT).show()
            }
            else -> {
                // 定位失败
                val errorMsg = when (location.locType) {
                    BDLocation.TypeServerError -> "服务端网络定位失败"
                    BDLocation.TypeNetWorkException -> "网络不通导致定位失败"
                    BDLocation.TypeCriteriaException -> "无法获取有效定位依据"
                    else -> "定位失败，错误码: ${location.locType}"
                }
                Toast.makeText(this, errorMsg, Toast.LENGTH_LONG).show()
            }
        }
    }
    
    /**
     * 更新地图位置显示
     */
    private fun updateMapLocation(latitude: Double, longitude: Double) {
        val latLng = LatLng(latitude, longitude)
        
        // 构造定位数据
        val locData = MyLocationData.Builder()
            .accuracy(100f)
            .direction(0f)
            .latitude(latitude)
            .longitude(longitude)
            .build()
        
        // 设置定位数据
        baiduMap.setMyLocationData(locData)
        
        // 如果是第一次定位，移动地图到当前位置
        if (isFirstLocation) {
            isFirstLocation = false
            val mapStatus = MapStatusUpdateFactory.newLatLngZoom(latLng, 16f)
            baiduMap.animateMapStatus(mapStatus)
        }
        
        // 添加标记点
        val markerOptions = MarkerOptions()
            .position(latLng)
            .icon(BitmapDescriptorFactory.fromResource(com.example.exam.R.drawable.ic_launcher_foreground))
        baiduMap.addOverlay(markerOptions)
    }
    
    /**
     * 更新位置信息UI显示
     */
    private fun updateLocationUI(latitude: Double, longitude: Double, address: String, time: String) {
        binding.apply {
            // 显示位置信息布局
            locationInfoLayout.visibility = View.VISIBLE
            
            // 更新文本内容
            tvLatLng.text = "经纬度: ${String.format("%.6f", latitude)}, ${String.format("%.6f", longitude)}"
            tvAddress.text = "地址: $address"
            tvLocationTime.text = "定位时间: $time"
        }
    }
    
    /**
     * 保存位置信息到SharedPreferences
     */
    private fun saveLocationToSP(latitude: Double, longitude: Double, address: String, time: String) {
        try {
            val editor = sharedPreferences.edit()
            editor.putFloat("latitude", latitude.toFloat())
            editor.putFloat("longitude", longitude.toFloat())
            editor.putString("address", address)
            editor.putString("location_time", time)
            editor.putLong("save_timestamp", System.currentTimeMillis())
            editor.apply()
            
            // 可选：显示保存成功提示
            // Toast.makeText(this, "位置信息已保存", Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "保存位置信息失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
    
    /**
     * 加载之前保存的位置信息
     */
    private fun loadSavedLocationInfo() {
        try {
            val latitude = sharedPreferences.getFloat("latitude", 0f).toDouble()
            val longitude = sharedPreferences.getFloat("longitude", 0f).toDouble()
            val address = sharedPreferences.getString("address", "") ?: ""
            val time = sharedPreferences.getString("location_time", "") ?: ""
            
            // 如果有保存的位置信息，显示出来
            if (latitude != 0.0 && longitude != 0.0 && address.isNotEmpty()) {
                updateLocationUI(latitude, longitude, address, time)
                updateMapLocation(latitude, longitude)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    
    /**
     * 权限请求结果处理
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        
        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
            val allPermissionsGranted = grantResults.all { it == PackageManager.PERMISSION_GRANTED }
            
            if (allPermissionsGranted) {
                // 所有权限都已授予，开始定位
                initLocationClient()
            } else {
                // 权限被拒绝
                Toast.makeText(this, "需要位置权限才能使用定位功能", Toast.LENGTH_LONG).show()
            }
        }
    }
    
    /**
     * Activity生命周期方法
     */
    override fun onResume() {
        super.onResume()
        mapView.onResume()
    }
    
    override fun onPause() {
        super.onPause()
        mapView.onPause()
    }
    
    override fun onDestroy() {
        super.onDestroy()
        // 关闭定位图层
        baiduMap.isMyLocationEnabled = false
        
        // 停止定位客户端
        if (::locationClient.isInitialized) {
            locationClient.stop()
        }
        
        // 销毁地图视图
        mapView.onDestroy()
    }
    

}